package com.margo.project.zipkin.httpclient;

import java.io.IOException;


import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MargoHttpClientService {
	
	private Logger logger=LoggerFactory.getLogger(MargoHttpClientService.class);

	@Autowired
	private CloseableHttpClient httpclient;
	
	/**
	 * 访问百度
	 */
	public void httpRequest() {
		
		//1、
		String url="http://www.baidu.com";
		//CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		
		// 2、HttpGet(final String uri)：创建 http get 请求对象
		HttpGet httpGet = new HttpGet(url);
		 
		// 3、设置超时时间、请求时间、socket 时间都为 15 秒，允许重定向
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(15000)
		        .setConnectionRequestTimeout(15000)
		        .setSocketTimeout(15000)
		        .setRedirectsEnabled(true)
		        .build();
		httpGet.setConfig(requestConfig);
		 
		// 4、CloseableHttpResponse execute(final HttpUriRequest request)：执行请求
		// 如果连接不上服务器，则抛出:java.net.ConnectException: Connection refused: connect
		CloseableHttpResponse httpResponse;
		try {
			httpResponse = httpclient.execute(httpGet);
			 // 5、获取响应结果, 状态码 200 表示请求成功
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			logger.info("响应状态码：" + statusCode);
		}  catch (IOException e) {
			logger.info("请求报错",e);
		}
	}

	/**
	 * 访问另一个zipkin客户端
	 */
	public void sentinelRequest() {
		//1、
		String url="http://localhost:8080/getOrder?orderId=111";
		//CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		
		// 2、HttpGet(final String uri)：创建 http get 请求对象
		HttpGet httpGet = new HttpGet(url);
		 
		// 3、设置超时时间、请求时间、socket 时间都为 15 秒，允许重定向
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(15000)
		        .setConnectionRequestTimeout(15000)
		        .setSocketTimeout(15000)
		        .setRedirectsEnabled(true)
		        .build();
		httpGet.setConfig(requestConfig);
		 
		// 4、CloseableHttpResponse execute(final HttpUriRequest request)：执行请求
		// 如果连接不上服务器，则抛出:java.net.ConnectException: Connection refused: connect
		CloseableHttpResponse httpResponse;
		try {
			httpResponse = httpclient.execute(httpGet);
			 // 5、获取响应结果, 状态码 200 表示请求成功
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			logger.info("响应状态码：" + statusCode);
		}  catch (IOException e) {
			logger.info("请求报错",e);
		}
		
	}
}
